package com.hbsoft.wechat.service;

import com.hb.bean.CallResult;
import com.hbsoft.wechat.bean.Organize;
import com.hbsoft.wechat.bean.PerOrgan;
import com.hbsoft.wechat.bean.WXUser;
import com.hbsoft.wechat.dao.service.OrganizeDaoService;
import com.hbsoft.wechat.dao.service.PerOrganDaoService;
import com.hbsoft.wechat.dao.service.WXUserDaoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class OrganizeService {

    @Autowired
    OrganizeDaoService organizeDaoService;

    @Autowired
    WXUserDaoService wXUserDaoService;

    @Autowired
    PerOrganDaoService perOrganDaoService;

    @Transactional
    public CallResult<String> addOrganize(Organize organize) throws Exception {
        CallResult<String> result = new CallResult<>();
        try {
            WXUser user = new WXUser();
            user.setOpenid(organize.getOpendId());
            WXUser person = wXUserDaoService.getByField(user);
            if (null != person) {
                organize.setCreatePerson(organize.getOpendId());
                organize.setCreateTime(new Date());
                Integer organizeId = organizeDaoService.addPrikey(organize);
                PerOrgan po = new PerOrgan();
                po.setOrganizeId(organizeId);
                po.setPersonId(person.getOpenid());
                po.setBindTime(new Date());
                po.setStop(0);
                perOrganDaoService.add(po);
                result.setCode(0);
                result.setMessage("创建成功");
            }else {
                result.setCode(400);
                result.setMessage("请注册");
                return result;
            }

        }catch (Exception e) {
            result.setCode(400);
            result.setMessage("创建失败");
            e.printStackTrace();
        }
        return result;
    }

    public List<Organize> findOrganByOpendId(Organize organize) {
        return organizeDaoService.findOrganByOpendId(organize);
    }
}
